<template>
  <div class="dingdan-page">
    <!-- 头部标题 -->
    <header class="dingdan-header">
      <div class="header-content">
        <!-- 返回按钮 -->
        <router-link to="/showshouye" class="go-back-btn"><</router-link>
        <!-- 标题 -->
        <h2 class="title">我的订单</h2>
      </div>
    </header>
    <!-- 标签导航 -->
    <nav class="dingdan-nav">
      <button :class="{ active: currentTab === 'all' }" @click="changeTab('all')">全部订单</button>
      <button :class="{ active: currentTab === 'pingjia' }" @click="changeTab('pingjia')">我的评价</button>
      <button :class="{ active: currentTab === 'refund' }" @click="changeTab('refund')">退款/售后</button>
    </nav>
    <!-- 主要内容区 -->
    <main class="dingdan-main">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <div class="spinner"></div>
        <p>加载中...</p>
      </div>
      <!-- 全部订单 -->
      <div v-else-if="currentTab === 'all'">
        <div v-if="allDingdans.length === 0" class="empty-state">
          <img :src="emptyDingdanImg" alt="无订单" class="empty-img">
          <p>暂无订单</p>
          <button class="go-btn" @click="showshouye">去逛逛</button>
        </div>
        <div class="dingdan-list">
          <div v-for="dingdan in allDingdans" :key="dingdan.ddid" class="dingdan-item">
            <!-- 商家信息区（优化） -->
            <div class="dingdan-shangjia">
              <div class="shangjia-left">
                <el-icon><Shop /></el-icon>
                <span class="shangjia-name" @click="goToShangjia(dingdan.sjid)">{{ dingdan.name || `商家${dingdan.sjid}` }}</span>
              </div>
              <div class="shangjia-right">
                <span class="order-time">{{ formatTime(dingdan.ddsj) || '未知时间' }}</span>
                <span :class="['order-status', getZhuangTaiClass(dingdan.ddzt)]">{{ dingdan.ddzt }}</span>
              </div>
            </div>

            <!-- 订单商品区 -->
            <div class="dingdan-caipin">
              <div v-for="(caipin, index) in dingdan.caiPinDetails" :key="caipin.xqid" class="caipin-item">
                <img :src="url+caipin.cptp" alt="菜品图片" class="caipin-img">
                <div class="caipin-info">
                  <p class="caipin-name" style="font-weight: bolder">{{ caipin.cpmc}}</p>
                  <div class="caipin-extra">
                    <span class="caipin-count">数量：{{ caipin.cpsl }}</span>
                    <span class="caipin-price">￥{{ parseFloat(caipin.cpdj).toFixed(2) }}</span>
                  </div>
                </div>
              </div>
              <!-- 空状态优化 -->
              <div v-if="!dingdan.caiPinDetails || dingdan.caiPinDetails.length === 0" class="caipin-empty">
                <p>暂无菜品详情</p>
              </div>
            </div>

            <!-- 订单底部（优化） -->
            <div class="dingdan-footer">
              <div class="footer-left">
                <p class="total-text">合计：</p>
                <p class="dingdan-zongjia">￥{{ dingdan.tprice ? parseFloat(dingdan.tprice).toFixed(2) : '0.00' }}</p>
                <p class="total-count" v-if="dingdan.caiPinDetails && dingdan.caiPinDetails.length">
                  共{{ dingdan.caiPinDetails.length }}件商品
                </p>
              </div>
              <div class="dingdan-caozuo">
                <!-- 添加删除订单按钮 -->
                <button class="caozuo-btn" @click="deleteOrder(dingdan)" type="danger">删除订单</button>
                <!-- 修改：使用弹窗展示详情而不是跳转页面 -->
                <button class="caozuo-btn" @click="showDetailDialog(dingdan)">订单详情</button>
                <!-- 添加支付功能 -->
                <button v-if="dingdan.ddzt === '未支付'" class="caozuo-btn primary" @click="showPaymentDialog(dingdan)">去支付</button>
                <button
                    v-if="dingdan.ddzt === '已支付'"
                    class="caozuo-btn"
                    @click.stop="handlePingjiaAction(dingdan)">
                  {{ hasPingjia(dingdan.ddid) ? '查看评价' : '写评价' }}
                </button>
                <!-- 再来一单按钮（强化） -->
                <button v-if="dingdan.ddzt === '已支付'" class="caozuo-btn again-btn" @click.stop="zaiLaiYiDan(dingdan.sjid)">
                  <el-icon><ShoppingCart /></el-icon>再来一单
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 我的评价 -->
      <div v-else-if="currentTab === 'pingjia'">
        <div v-if="myPingjia.length === 0" class="empty-state">
          <img :src="emptyPingjiaImg" alt="无评价" class="empty-img">
          <p>暂无评价</p>
          <button class="go-btn" @click="changeTab('all')">查看可评价订单</button>
        </div>
        <div class="pingjia-list">
          <div v-for="pj in myPingjia" :key="pj.pjid" class="pingjia-item":id="'pingjia-' + pj.ddid">
            <!-- 订单基本信息 -->
            <div class="dingdan-shangjia pingjia-header">
              <div class="shangjia-left">
                <el-icon><Shop /></el-icon>
                <span class="shangjia-name" @click="goToShangjia(pj.sjid)">{{ pj.shangjiaName }}</span>
              </div>
              <div class="shangjia-right">
                <span class="order-time">{{ formatTime(pj.pjsj) }}</span>
              </div>
            </div>

            <!-- 订单商品信息 -->
            <div class="dingdan-caipin pingjia-caipin">
              <div v-for="(caipin, index) in pj.caiPinDetails" :key="index" class="caipin-item">
                <img :src=" url+caipin.cptp" alt="菜品图片" class="caipin-img">
                <div class="caipin-info">
                  <p class="caipin-name" style="font-weight: bolder">{{ caipin.cpmc || '未知菜品' }}</p>
                  <div class="caipin-extra">
                    <span class="caipin-count">数量：{{ caipin.cpsl }}</span>
                    <span class="caipin-price">￥{{ parseFloat(caipin.cpdj).toFixed(2) }}</span>
                  </div>
                </div>
              </div>
              <div v-if="!pj.caiPinDetails || pj.caiPinDetails.length === 0" class="caipin-empty">
                <p>暂无菜品详情</p>
              </div>
            </div>
            <!-- 评价内容 -->
            <div class="pingjia-neirong">
              <div class="pingjia-pingfen">
                <span>评分：</span>
                <span v-for="i in 5" :key="i" class="star" :class="{ active: i <= pj.sjpfNum }">★</span>
              </div>
              <p class="pingjia-text">{{ pj.pjnr }}</p>
              <div class="pingjia-tupian" v-if="pj.sctp">
                <img :src="url+pj.sctp" alt="评价图片" class="tupian-item">
              </div>
              <div class="shangjia-huifu" v-if="pj.sjhf">
                <p class="huifu-title">商家回复：</p>
                <p class="huifu-neirong">{{ pj.sjhf }}</p>
                <p class="huifu-shijian">{{ formatTime(pj.hfsj) }}</p>
              </div>
              <!-- 删除评价按钮 -->
              <div style="text-align: right; margin-top: 10px; padding-top: 10px; border-top: 0px dashed #eee;">
                <el-button
                    type="danger"
                    size="small"
                    @click.stop="deletePingjia(pj)"
                    :loading="pj.deleting">
                  删除评价
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 退款/售后 -->
      <div v-else-if="currentTab === 'refund'">
        <div v-if="refundDingdan.length === 0" class="empty-state">
          <img :src="emptyRefundImg" alt="无退款" class="empty-img">
          <p>暂无退款/售后订单</p>
        </div>
        <div class="refund-list">
          <div v-for="dingdan in refundDingdan" :key="dingdan.ddid" class="refund-item">
            <div class="refund-shangjia">
              <span class="shangjia-name" @click="goToShangjia(dingdan.sjid)">{{ dingdan.name || `商家${dingdan.sjid}` }}</span>
              <span :class="getZhuangTaiClass(dingdan.ddzt)">{{ dingdan.ddzt }}</span>
            </div>
            <div class="refund-info">
              <p>订单时间：{{ formatTime(dingdan.ddsj) }}</p>
              <p>订单地址：{{ dingdan.dddz }}</p>
              <p>退款金额：￥{{ dingdan.tPrice ? parseFloat(dingdan.tPrice).toFixed(2) : '0.00' }}</p>
            </div>
            <div class="refund-footer">
              <button class="caozuo-btn" @click="showDetailDialog(dingdan)">查看详情</button>
              <button class="caozuo-btn" @click="deleteOrder(dingdan)" type="danger">删除订单</button>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 订单详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="订单信息" width="60%" top="10vh" destroy-on-close>
      <show-d-d-x-q
          ref="detailPageRef"
          @closeDialog="detailDialogVisible = false">
      </show-d-d-x-q>
    </el-dialog>

    <!-- 支付弹窗 -->
    <el-dialog v-model="paymentDialogVisible" title="支付确认" width="400px" destroy-on-close>
      <div class="payment-dialog">
        <div class="payment-qrcode">
          <img src="../../assets/二维码.png" alt="支付二维码" class="qrcode-img">
        </div>
        <p class="payment-amount">支付金额: ¥{{ currentPaymentOrder.tprice ? parseFloat(currentPaymentOrder.tprice).toFixed(2) : '0.00' }}</p>
        <div class="payment-buttons">
          <el-button @click="cancelPayment" type="info">取消支付</el-button>
          <el-button @click="confirmPayment" type="success">确认支付</el-button>
        </div>
      </div>
    </el-dialog>
  </div>

  <!-- 评价弹窗 -->
  <el-dialog v-model="ratingDialogVisible" title="写评价" width="500px" destroy-on-close>
    <el-form :model="ratingForm" :rules="ratingRules" ref="ratingFormRef" label-width="80px">
      <el-form-item label="评分" prop="sjpf">
        <el-rate v-model="ratingForm.sjpf" :max="5" show-score></el-rate>
      </el-form-item>
      <el-form-item label="评价内容" prop="pjnr">
        <el-input
            v-model="ratingForm.pjnr"
            type="textarea"
            :rows="4"
            placeholder="请填写您的评价内容"
            maxlength="100"
            show-word-limit
            :class="{ 'exceed-limit': ratingForm.pjnr.length > 100 }">
        </el-input>
      </el-form-item>
      <!-- 简化的图片上传 -->
      <el-form-item label="评论图片" prop="avatar">
        <el-upload drag style="width:100%"
                   action="/api/file/upload"
                   :on-success="handleFileUploadSuccess"
        >
          <el-icon class="el-icon--upload"><upload-filled/></el-icon>
          <div class="el-upload__text">将头像图片拖拽到此处，或 <em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip">支持 jpg/png 格式， 大小不超过 5M</div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancelRating">取消</el-button>
        <el-button type="primary" @click="submitRating">提交评价</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 图片预览弹窗 -->
  <el-dialog v-model="previewVisible" title="图片预览">
    <img :src="previewImageUrl" style="width: 100%" alt="预览图片" />
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { useUserStore } from "../stores/user";
import { storeToRefs } from "pinia";
import { Shop, ShoppingCart } from '@element-plus/icons-vue';
import ShowDDXQ from "../ddxiangqing/ShowDDXQ.vue";
import emptyDingdanImg from '../../assets/logo1.png';
import emptyPingjiaImg from '../../assets/logo1.png';
import emptyRefundImg from '../../assets/logo1.png';
import defaultCaipinImg from '../../assets/logo1.png';
import {ElMessage, ElMessageBox} from 'element-plus';

const url = "http://localhost:8088/team/upload/"
// 路由实例
const router = useRouter();

// 响应式数据
const currentTab = ref('all'); // 当前标签页
const loading = ref(true); // 加载状态
const dingdanList = ref([]); // 所有订单
const pingjiaList = ref([]); // 所有评价
const shangjiaMap = ref({}); // 商家信息映射
const caiPinCache = ref({}); // 菜品信息缓存

// 订单详情弹窗相关
const detailDialogVisible = ref(false);
const detailPageRef = ref();

// 支付弹窗相关
const paymentDialogVisible = ref(false);
const currentPaymentOrder = ref({});

const ratingRules = {
  sjpf: [{ required: true, message: '请评分', trigger: 'change' }],
  pjnr: [{ required: true, message: '请输入评价内容', trigger: 'blur' }]
};

const userInfo = ref({});

// 切换标签页
const changeTab = (tab) => {
  currentTab.value = tab;
};

// 格式化时间
const formatTime = (time) => {
  if (!time) return '';
  const date = new Date(time);
  if (isNaN(date.getTime())) return '无效时间';
  return `${date.getFullYear()}-${
      (date.getMonth() + 1).toString().padStart(2, '0')
  }-${
      date.getDate().toString().padStart(2, '0')
  } ${
      date.getHours().toString().padStart(2, '0')
  }:${
      date.getMinutes().toString().padStart(2, '0')
  }`;
};

// 添加评价弹窗相关
const ratingDialogVisible = ref(false);
const currentRatingOrder = ref({});
const ratingFormRef = ref();
const ratingForm = ref({
  yhid: '',
  ddid: '',
  sjid: '',
  pjnr: '',
  sjpf: null,
  sctp: ''
});
const handleFileUploadSuccess = (fileName) => {
  if (fileName != null || fileName !== '') {
    ratingForm.value.sctp = fileName;
    ElMessage({type: 'success',message:'文件上传成功'})
  }else{
    ElMessage({type: 'error',message:'文件上传失败'})
  }
}
const ratingImageList = ref([]);
const previewVisible = ref(false);
const previewImageUrl = ref('');


// 订单状态样式
const getZhuangTaiClass = (zhuangtai) => {
  const classMap = {
    '已支付': 'zhuangtai-chenggong',
    '未支付': 'zhuangtai-dengdai',
    '配送中': 'zhuangtai-peisong',
    '已取消': 'zhuangtai-quxiao',
    '退款/售后': 'zhuangtai-tuihuan',
    '已退款': 'zhuangtai-chenggong',
    '退款失败': 'zhuangtai-quxiao'
  };
  return classMap[zhuangtai] || '';
};

// 计算属性：全部订单
const allDingdans = computed(() => {
  return dingdanList.value.map(dingdan => {
    const shangjia = shangjiaMap.value[dingdan.sjid];
    return {
      ...dingdan,
      name: shangjia ? shangjia.name : `商家${dingdan.sjid}`
    };
  });
});

// 计算属性：我的评价
const myPingjia = computed(() => {
  return pingjiaList.value.map(pj => ({
    ...pj,
    shangjiaName: shangjiaMap.value[pj.sjid]?.name || `商家${pj.sjid}`,
    sjpfNum: parseInt(pj.sjpf) || 5
  }));
});

// 计算属性：退款订单
const refundDingdan = computed(() => {
  return allDingdans.value.filter(dingdan =>
      ['退款/售后', '已退款', '退款失败'].includes(dingdan.ddzt)
  );
});

// 跳转到商家详情页
const goToShangjia = (sjid) => {
  router.push({
    path: '/sjcaipin',
    query: {
      sjid: sjid
    }
  });
};

// 显示订单详情弹窗
const showDetailDialog = (dingdan) => {
  detailDialogVisible.value = true;
  nextTick(() => {
    if (detailPageRef.value) {
      detailPageRef.value.handleShowData(dingdan);
    }
  });
};

// 显示支付弹窗
const showPaymentDialog = (dingdan) => {
  currentPaymentOrder.value = dingdan;
  paymentDialogVisible.value = true;
};

// 处理评价操作（写评价或查看评价）
// 检查订单是否已有评价
const hasPingjia = (ddid) => {
  return pingjiaList.value.some(pj => pj.ddid === ddid);
};

// 处理评价操作（写评价或查看评价）
const handlePingjiaAction = (dingdan) => {
  if (hasPingjia(dingdan.ddid)) {
    // 查看评价 - 跳转到评价tab并定位到对应评价
    changeTab('pingjia');
    // 使用nextTick确保DOM已更新
    nextTick(() => {
      setTimeout(() => {
        const element = document.getElementById(`pingjia-${dingdan.ddid}`);
        if (element) {
          element.scrollIntoView({ behavior: 'smooth', block: 'center' });
          // 添加一个高亮效果
          element.style.transition = 'background-color 0.5s';
          element.style.backgroundColor = '#fff3cd';
          setTimeout(() => {
            element.style.backgroundColor = '';
          }, 2000);
        }
      }, 100);
    });
  } else {
    // 写评价
    showRatingDialog(dingdan);
  }
};

// 显示评价弹窗
const showRatingDialog = (dingdan) => {
  currentRatingOrder.value = dingdan;
  ratingForm.value = {
    yhid: userInfo.value.yhid,
    ddid: dingdan.ddid,
    sjid: dingdan.sjid,
    pjnr: '',
    sjpf: null,
  };
  ratingImageList.value = [];
  ratingDialogVisible.value = true;
};

// 取消评价
const cancelRating = () => {
  ratingDialogVisible.value = false;
  currentRatingOrder.value = {};
  ratingForm.value = {
    yhid: '',
    ddid: '',
    sjid: '',
    pjnr: '',
    sjpf: null,
    sctp: ''
  };
};

// 提交评价
const submitRating = async () => {
  try {
    // 表单验证
    await ratingFormRef.value.validate();


    // 构造评价数据
    const ratingData = {
      yhid: parseInt(ratingForm.value.yhid),
      ddid: parseInt(ratingForm.value.ddid),
      sjid: parseInt(ratingForm.value.sjid),
      pjnr: ratingForm.value.pjnr,
      sjpf: ratingForm.value.sjpf ? ratingForm.value.sjpf.toString() : '5',
      sctp: ratingForm.value.sctp,
      pjsj: new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }).replace(/\//g, '-')
    };


    // 发送评价数据到后端
    const { data } = await axios.post('/api/pingjia', ratingData);
    console.log('返回后端的评价数据:', data);
    if (data.code === 200) {
      ElMessage.success('评价提交成功');

      // 关闭弹窗并重置表单
      ratingDialogVisible.value = false;
      currentRatingOrder.value = {};
      ratingForm.value = {
        yhid: '',
        ddid: '',
        sjid: '',
        pjnr: '',
        sjpf: null,
        sctp: ''
      };
      ratingImageList.value = [];

      // 刷新评价列表
      await getPingjiaList();
    } else {
      ElMessage.error(data.message || '评价提交失败');
    }
  } catch (error) {
    console.error('提交评价失败:', error);
    ElMessage.error('评价提交失败，请重试');
  }
};

// 删除评价功能
const deletePingjia = async (pingjia) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除这条评价吗？`,
        '删除评价',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    );

    const { data } = await axios.delete(`/api/pingjia/${pingjia.pjid}`);
    if (data.code === 200) {
      ElMessage.success('删除成功');
      // 刷新评价列表
      await getPingjiaList();
    } else {
      ElMessage.error(data.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
      console.error(error);
    }
  }
};

// 取消支付
const cancelPayment = () => {
  paymentDialogVisible.value = false;
  currentPaymentOrder.value = {};
};

// 确认支付
const confirmPayment = async () => {
  try {
    // 更新订单状态为已支付
    const updatedOrder = {
      ...currentPaymentOrder.value,
      ddzt: '已支付'
    };

    const { data } = await axios.put('/api/dingdan', updatedOrder);
    if (data.code === 200) {
      // 更新本地订单状态
      const orderIndex = dingdanList.value.findIndex(d => d.ddid === currentPaymentOrder.value.ddid);
      if (orderIndex !== -1) {
        dingdanList.value[orderIndex].ddzt = '已支付';
      }

      // 关闭支付弹窗
      paymentDialogVisible.value = false;
      currentPaymentOrder.value = {};

      ElMessage.success('支付成功');
    } else {
      ElMessage.error(data.message || '支付失败');
    }
  } catch (error) {
    ElMessage.error('支付失败');
    console.error(error);
  }
};

// 删除订单功能
const deleteOrder = async (dingdan) => {
  await ElMessageBox.confirm(
      `确定要删除这条订单记录吗？`,
      '删除订单',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  );

  const {data} = await axios.delete(`/api/dingdan/${dingdan.ddid}`)
  console.log(data);
  if(data.code === 200){
    ElMessage.success('删除成功');
    // 删除后刷新列表
    await getDingdanList();
  }else{
    ElMessage.error(data.message);
  }
};

// 再来一单
const zaiLaiYiDan = (sjid) => {
  router.push(`/sjcaipin?sjid=${sjid}`);
};

// 去首页
const showshouye = () => {
  router.push('/showshouye');
};

// 获取商家信息
const getShangjiaInfo = async (sjids) => {
  try {
    const uniqueSjids = [...new Set(sjids.filter(sjid => sjid))];
    for (const sjid of uniqueSjids) {
      if (!shangjiaMap.value[sjid]) {
        try {
          const { data } = await axios.get(`/api/shangjia/id/${sjid}`);
          if (data.code === 200 && data.data) {
            shangjiaMap.value[sjid] = data.data;
          }
        } catch (error) {
          console.error(`获取商家${sjid}信息失败:`, error);
        }
      }
    }
  } catch (error) {
    console.error('获取商家信息失败:', error);
  }
};

// 获取菜品信息
const getCaiPinInfo = async (cpids) => {
  try {
    const uniqueCpids = [...new Set(cpids.filter(cpid => cpid))];
    for (const cpid of uniqueCpids) {
      if (!caiPinCache.value[cpid]) {
        try {
          const { data } = await axios.get(`/api/caiPin/${cpid}`);
          if (data.code === 200 && data.data) {
            caiPinCache.value[cpid] = data.data;
          }
        } catch (error) {
          console.error(`获取菜品${cpid}信息失败:`, error);
        }
      }
    }
  } catch (error) {
    console.error('获取菜品信息失败:', error);
  }
};

// 获取评价详情信息（包括菜品信息）
const getPingjiaDetails = async (pingjias) => {
  try {
    for (const pj of pingjias) {
      try {
        // 获取订单信息
        const { data: orderData } = await axios.get(`/api/dingdan/${pj.ddid}`);
        if (orderData.code === 200 && orderData.data) {
          // 获取订单详情（菜品信息）
          const { data: detailData } = await axios.get(`/api/xiangqing/byddid/${pj.ddid}`);
          if (detailData.code === 200 && detailData.data && Array.isArray(detailData.data) && detailData.data.length > 0) {
            const cpids = detailData.data.map(detail => detail.cpid).filter(cpid => cpid);
            await getCaiPinInfo(cpids);
            const caiPinDetails = [];
            for (const detail of detailData.data) {
              if (detail) {
                const caipinInfo = caiPinCache.value[detail.cpid];
                caiPinDetails.push({
                  ...detail,
                  ...caipinInfo
                });
              }
            }
            pj.caiPinDetails = caiPinDetails;
          } else {
            pj.caiPinDetails = [];
          }
        }
      } catch (error) {
        console.error(`获取评价${pj.pjid}的订单详情失败:`, error);
        pj.caiPinDetails = [];
      }
    }
  } catch (error) {
    console.error('获取评价详情失败:', error);
  }
};

// 获取订单详情信息
const getDingdanDetails = async (dingdans) => {
  try {
    for (const dingdan of dingdans) {
      try {
        const { data: detailData } = await axios.get(`/api/xiangqing/byddid/${dingdan.ddid}`);
        if (detailData.code === 200 && detailData.data && Array.isArray(detailData.data) && detailData.data.length > 0) {
          const cpids = detailData.data.map(detail => detail.cpid).filter(cpid => cpid);
          await getCaiPinInfo(cpids);
          const caiPinDetails = [];
          for (const detail of detailData.data) {
            if (detail) {
              const caipinInfo = caiPinCache.value[detail.cpid];
              caiPinDetails.push({
                ...detail,
                ...caipinInfo
              });
            }
          }
          dingdan.caiPinDetails = caiPinDetails;
        } else {
          dingdan.caiPinDetails = [];
        }
      } catch (error) {
        console.error(`获取订单${dingdan.ddid}详情失败:`, error);
        dingdan.caiPinDetails = [];
      }
    }
  } catch (error) {
    console.error('获取订单详情失败:', error);
  }
};

// 获取订单数据
const getDingdanList = async () => {
  try {
    const { data } = await axios.get(`/api/dingdan/users/${userInfo.value.yhid}`);
    if (data.code === 200) {
      dingdanList.value = data.data && Array.isArray(data.data) ? data.data : [];
      const sjids = dingdanList.value.map(dingdan => dingdan.sjid).filter(sjid => sjid);
      await getShangjiaInfo(sjids);
      await getDingdanDetails(dingdanList.value);
    } else {
      console.error('获取订单失败：' + (data.message || '未知错误'));
      dingdanList.value = [];
    }
  } catch (error) {
    console.error('获取订单失败:', error);
    dingdanList.value = [];
  } finally {
    loading.value = false;
  }
};

// 获取评价数据
const getPingjiaList = async () => {
  try {
    const { data } = await axios.get(`/api/pingjia/users/${userInfo.value.yhid}`);
    if (data.code === 200) {
      pingjiaList.value = data.data && Array.isArray(data.data) ? data.data : [];
      const sjids = pingjiaList.value.map(pingjia => pingjia.sjid).filter(sjid => sjid);
      await getShangjiaInfo(sjids);
      await getPingjiaDetails(pingjiaList.value);
    } else {
      console.error('获取评价失败：' + (data.message || '未知错误'));
      pingjiaList.value = [];
    }
  } catch (error) {
    console.error('获取评价失败:', error);
    pingjiaList.value = [];
  }
};

// 页面挂载时加载数据
onMounted(() => {
  userInfo.value = JSON.parse(localStorage.getItem('userInfo')) || {};
  getDingdanList();
  getPingjiaList();
});
</script>

<style scoped>
.dingdan-page {
  font-family: "Microsoft YaHei", sans-serif;
  background-color: #f5f5f5;
  min-height: 100vh;
  color: #333;
  margin: 0;
  padding: 0;
}

.dingdan-header {
  background-color: #f58147;
  color: white;
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
}

.title {
  margin: 0;
  font-size: 18px;
  flex: 1;
  text-align: center;
}

.go-back-btn {
  color: white;
  text-decoration: none;
  cursor: pointer;
  font-size: 20px;
}

.dingdan-nav {
  display: flex;
  background-color: white;
  border-bottom: 1px solid #eee;
}

.dingdan-nav button {
  flex: 1;
  padding: 14px 0;
  border: none;
  background: none;
  font-size: 16px;
  color: #666;
  position: relative;
  cursor: pointer;
}

.dingdan-nav button.active {
  color: #f58147;
}

.dingdan-nav button.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #f58147;
}

.dingdan-main {
  padding: 10px;
}

.loading-state {
  background-color: white;
  border-radius: 8px;
  padding: 60px 20px;
  text-align: center;
  margin-bottom: 10px;
}

.spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto 16px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #f58147;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-state {
  background-color: white;
  border-radius: 8px;
  padding: 40px 20px;
  text-align: center;
  margin-bottom: 10px;
}

.empty-img {
  width: 20vw;
  max-width: 120px;
  height: auto;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-state p {
  color: #999;
  margin: 0 0 20px;
}

.go-btn {
  padding: 8px 24px;
  background-color: #f58147;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
}

/* 订单列表样式（优化） */
.dingdan-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.dingdan-item {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: transform 0.2s;
}

.dingdan-item:hover {
  transform: translateY(-2px);
}

/* 商家信息区样式 */
.dingdan-shangjia {
  padding: 14px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f5f5f5;
  background-color: #fafafa;
}

.shangjia-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.shangjia-name {
  font-weight: 500;
  font-size: 15px;
  cursor: pointer;
  color: #333;
}

.shangjia-name:hover {
  color: #f58147;
}

.shangjia-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.order-time {
  font-size: 12px;
  color: #999;
  white-space: nowrap;
}

.order-status {
  font-weight: 500;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 13px;
}

/* 订单商品区样式 */
.dingdan-caipin {
  padding: 16px;
  border-bottom: 1px solid #f5f5f5;
}

.caipin-item {
  display: flex;
  padding: 10px 0;
  border-bottom: 1px dashed #f0f0f0;
}

.caipin-item:last-child {
  border-bottom: none;
}

.caipin-img {
  width: 70px;
  height: 70px;
  object-fit: cover;
  border-radius: 6px;
  margin-right: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.caipin-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 4px;
}

.caipin-name {
  margin: 0;
  font-size: 15px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}

.caipin-spec {
  margin: 0;
  font-size: 12px;
  color: #999;
}

.caipin-extra {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 4px;
}

.caipin-count {
  font-size: 13px;
  color: #666;
}

.caipin-price {
  font-size: 14px;
  color: #f53f3f;
  font-weight: 500;
}

.caipin-empty {
  padding: 30px 0;
  text-align: center;
  color: #999;
  font-size: 14px;
  background-color: #fafafa;
  border-radius: 4px;
}

/* 订单底部样式 */
.dingdan-footer {
  padding: 14px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fafafa;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.total-text {
  color: #666;
  font-size: 14px;
}

.dingdan-zongjia {
  margin: 0;
  color: #f53f3f;
  font-weight: 600;
  font-size: 15px;
}

.total-count {
  margin: 0;
  font-size: 12px;
  color: #999;
}

.dingdan-caozuo {
  display: flex;
  gap: 10px;
}

.caozuo-btn {
  padding: 6px 14px;
  border: 1px solid #f58147;
  background: none;
  color: #f58147;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 4px;
}

.caozuo-btn:hover {
  background-color: #fff5f0;
}

.caozuo-btn.primary {
  background-color: #f58147;
  color: white;
}

.caozuo-btn.primary:hover {
  background-color: #e8733e;
}

.caozuo-btn.again-btn {
  background-color: #4cd964;
  color: white;
  border-color: #4cd964;
}

.caozuo-btn.again-btn:hover {
  background-color: #3dd058;
  transform: scale(1.05);
}

/* 订单状态样式 */
.zhuangtai-chenggong { color: #00b42a; background-color: #f6ffed; }
.zhuangtai-dengdai { color: #ff7d00; background-color: #fff7e8; }
.zhuangtai-peisong { color: #1890ff; background-color: #e6f7ff; }
.zhuangtai-quxiao { color: #999; background-color: #f5f5f5; }
.zhuangtai-tuihuan { color: #f53f3f; background-color: #fff2f3; }

/* 我的评价样式 */
.pingjia-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

/* 评价高亮样式 */
.highlight {
  animation: highlight 2s ease;
}

@keyframes highlight {
  0% {
    background-color: #fff3cd;
  }
  100% {
    background-color: transparent;
  }
}

.pingjia-item {
  background-color: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  transition: background-color 0.3s;
}

.pingjia-header {
  border-bottom: 1px solid #f5f5f5;
  background-color: #fafafa;
}

.pingjia-caipin {
  padding: 16px;
  border-bottom: 1px solid #f5f5f5;
}

.pingjia-pingfen {
  color: #ddd;
  margin-bottom: 8px;
}

.pingjia-pingfen .star.active {
  color: #ffaa00;
}

.pingjia-neirong {
  margin-bottom: 12px;
}

.pingjia-text {
  margin: 0 0 12px;
  line-height: 1.5;
}

.pingjia-tupian {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.tupian-item {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.pingjia-shijian {
  margin: 0;
  font-size: 12px;
  color: #999;
}

.shangjia-huifu {
  background-color: #f9f9f9;
  padding: 12px;
  border-radius: 4px;
}

.huifu-title {
  margin: 0 0 8px;
  font-size: 14px;
  color: #666;
}

.huifu-neirong {
  margin: 0 0 4px;
  line-height: 1.5;
}

.huifu-shijian {
  margin: 0;
  font-size: 12px;
  color: #999;
  text-align: left;
}

/* 退款列表样式 */
.refund-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.refund-item {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.refund-shangjia {
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid #f5f5f5;
}

.refund-info {
  padding: 12px 16px;
  border-bottom: 1px solid #f5f5f5;
}

.refund-info p {
  margin: 0 0 8px;
  font-size: 14px;
}

.refund-footer {
  padding: 12px 16px;
  display: flex;
  justify-content: flex-end;
}

/* 支付弹窗样式 */
.payment-dialog {
  text-align: center;
  padding: 20px;
}

.payment-qrcode {
  margin-bottom: 20px;
}

.qrcode-img {
  width: 200px;
  height: 200px;
  object-fit: contain;
}

.payment-amount {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #f53f3f;
}

.payment-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.payment-buttons .el-button {
  width: 100px;
}

/* 响应式调整 */
@media (max-width: 375px) {
  .caozuo-btn {
    padding: 4px 8px;
    font-size: 12px;
  }

  .dingdan-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .dingdan-caozuo {
    width: 100%;
    justify-content: flex-end;
  }

  .shangjia-right {
    gap: 8px;
  }

  .order-time {
    display: none;
  }

  .caipin-img {
    width: 60px;
    height: 60px;
  }

  .shangjia-name {
    cursor: pointer;
  }

  .shangjia-name:hover {
    color: #f58147;
  }
}
</style>
